<script setup lang="tsx">
import { computed, onBeforeMount, ref } from "vue";
import { useElementSize } from "@vueuse/core";
import { ElTreeV2 } from "@chulei-ui/element-plus";
import { storeToRefs } from "pinia";
import { useCacheStore } from "../../sde/cache";
import { esi } from "../../repositories";
import { JITA_REGION_ID } from "../../constant";
import type { TreeNode } from "@chulei-ui/element-plus";
import UniverseTypeIcon from "~components/universe-type/UniverseTypeIcon.vue";
import UniverseTypePrice from "~components/universe-type/UniverseTypePrice.vue";
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
const cacheStore = useCacheStore();
const { categories } = storeToRefs(cacheStore);
const target = ref<HTMLElement>();
const { height } = useElementSize(target);
const search = ref<string>();
const marketTypeIds = ref(new Set<number>());
const showAll = ref<boolean>(false);
const showId = ref<boolean>(false);
const treeData = computed(() => {
  return categories.value
    .map((c) => {
      return {
        id: c.id,
        label: c.name,
        children: c.children
          .map((g) => {
            return {
              id: g.id,
              label: g.name,
              children: g.children
                .filter((t) => showAll.value || marketTypeIds.value.has(t.id))
                .map((type) => {
                  return {
                    id: type.id,
                    label: type.name,
                    leaf: true,
                  };
                })
                .filter((i) => i.label),
            };
          })
          .filter((c) => c.children?.length),
      };
    })
    .filter((c) => c.children?.length);
});

const onSearch = (query: string) => {
  treeRef.value!.filter(query);
};

const filterType = (query: string, node: TreeNode) => {
  //@ts-ignore
  return node.label!.includes(query);
};

onBeforeMount(async () => {
  const types = await esi.markets.types(JITA_REGION_ID);
  marketTypeIds.value = new Set(types);
});

defineOptions({
  name: "MarketTree",
});
</script>

<template>
  <div ref="target" class="h-full">
    <el-space>
      <el-input v-model="search" placeholder="请输入搜索条件" @input="onSearch" />
      <el-checkbox v-model="showAll" label="显示所有物品" />
      <el-checkbox v-model="showId" label="显示编号" />
    </el-space>
    <el-tree-v2 ref="treeRef" :filter-method="filterType" :data="treeData" :height="height - 50">
      <template #default="{ data }">
        <UniverseTypeIcon v-if="data.leaf" :id="data.id" />
        <UniverseTypePrice v-if="data.leaf" :id="data.id" />
        <span v-else> {{ data.label }} </span>
        <span v-if="showId">{{ data?.id }}</span>
      </template>
    </el-tree-v2>
  </div>
</template>
